import threading
import queue
from queue import Queue
import asyncio
from typing import List, Tuple
from bleak import BleakScanner, BleakClient
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData

import threading
from queue import Queue

# 用于存储接收到的数据的缓冲区
data_buffer = bytearray()
# 线程停止标志
thread_stop_event = threading.Event()

def ble_notification_thread(device_address, char_uuid):
    """
    用于接收BLE通知的线程函数
    """
    global data_buffer
    
    async def run_ble_client():
        try:
            async with BleakClient(device_address) as client:
                if not client.is_connected:
                    print("连接失败")
                    return
                
                print(f"成功连接到设备: {device_address}")
                
                # 定义通知处理函数
                def notification_handler(sender: int, data: bytearray) -> None:
                    """处理接收到的通知数据"""
                    global data_buffer
                    data_buffer.extend(data)  # 将新数据添加到缓冲区
                    
                    # 检查缓冲区是否达到或超过256字节
                    while len(data_buffer) >= 256:
                        # 提取前256字节
                        packet = data_buffer[:256]
                        # 从缓冲区移除已处理的数据
                        data_buffer = data_buffer[256:]
                        # 直接打印完整数据包
                        print(f"收到完整数据包 (256字节): {packet.hex()}")
                
                # 启动通知
                await client.start_notify(char_uuid, notification_handler)
                print(f"已启动从特征 {char_uuid} 的通知接收")
                
                # 保持线程运行，直到收到停止信号
                while not thread_stop_event.is_set():
                    await asyncio.sleep(0.1)
                
                # 停止通知
                await client.stop_notify(char_uuid)
                print("已停止通知接收")
                
        except Exception as e:
            print(f"BLE客户端错误: {e}")
    
    # 在线程内运行异步函数
    asyncio.run(run_ble_client())

def your_function():
    global last_call_time
    current_time = time.time()
    
    if last_call_time is not None:
        time_diff_ms = (current_time - last_call_time) * 1000  # 转换为毫秒
        if time_diff_ms > 1500:
            print(f"Warning: 超时，时间差为 {time_diff_ms:.2f} ms")
    
    # 更新上一次调用的时间
    last_call_time = current_time
    
    # 原始函数的操作
    print("Function executed")

def main():
    # 假设已经扫描并选择了设备
    device_address = "70:19:88:C6:D3:32"  # 替换为实际设备地址
    char_uuid = "0000fff1-0000-1000-8000-00805f9b34fb"  # 替换为实际特征UUID
    
    # 创建并启动BLE通知接收线程
    ble_thread = threading.Thread(
        target=ble_notification_thread,
        args=(device_address, char_uuid),
        daemon=True
    )
    ble_thread.start()
    
    try:
        # 主线程保持运行，等待用户输入
        input("按Enter键停止程序...\n")
    except KeyboardInterrupt:
        pass
    finally:
        # 设置停止标志
        thread_stop_event.set()
        # 等待线程结束
        ble_thread.join(timeout=2.0)
        print("程序已停止")

if __name__ == "__main__":
    main()